package com.yogurt.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yogurt.statistics.entity.Daily;
import com.yogurt.statistics.feign.UcenterClient;
import com.yogurt.statistics.mapper.DailyMapper;
import com.yogurt.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yogurt.statistics.vo.EchartsVO;
import com.yogurt.utils.Result;
import com.yogurt.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author yogurt
 * @since 2022-09-21
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public void registerNum(String day) {
        QueryWrapper<Daily> wrapper = new QueryWrapper<>();
        wrapper.eq("date_calculated", day);
        baseMapper.delete(wrapper);

        Result result = ucenterClient.countRegister(day);
        if (result.getCode().equals(ResultCode.SUCCESS)) {
            int count = (int) result.getData().get("countRegister");
            if (count == 0) {
                return;
            }
            Daily daily = new Daily();
            daily.setDateCalculated(day);
            daily.setRegisterNum(count);
            daily.setLoginNum(0);
            daily.setCourseNum(0);
            daily.setVideoViewNum(0);
            baseMapper.insert(daily);
        }
    }

    @Override
    public Map<String, Object> getShowData(EchartsVO vo) {
        QueryWrapper<Daily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated", vo.getBegin(), vo.getEnd());
        wrapper.select("date_calculated", vo.getType());
        List<Daily> list = baseMapper.selectList(wrapper);
        Map<String, Object> map = new HashMap<>();
        if (list.isEmpty()) {
            return map;
        }
        // 日期集合
        List<String> dateList = new ArrayList<>();
        // 数量集合
        List<Integer> numList = new ArrayList<>();
        for (Daily daily : list) {
            dateList.add(daily.getDateCalculated());
            switch (vo.getType()) {
                case "login_num":
                    numList.add(daily.getLoginNum());
                    break;
                case "register_num":
                    numList.add(daily.getRegisterNum());
                    break;
                case "video_view_num":
                    numList.add(daily.getVideoViewNum());
                    break;
                case "course_num":
                    numList.add(daily.getCourseNum());
                    break;
                default:
                    break;
            }
        }
        map.put("dateList", dateList);
        map.put("numList", numList);
        return map;
    }
}
